package com.yufu.camera.preview;

import android.content.Context;
import android.graphics.Color;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

import java.util.Arrays;

@CapacitorPlugin(name = "CameraPreview")
public class CameraPreviewPlugin extends Plugin {

  private final int containerViewId = 20;

  @PluginMethod
  public void echo(PluginCall call) {
    String value = call.getString("value");
    JSObject ret = new JSObject();
    call.resolve(ret);
  }

  @PluginMethod
  public void start(PluginCall call) throws CameraAccessException {

//    CameraManager cameraManager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
//    String[] cameraIds = cameraManager.getCameraIdList();
//
//    System.out.println("11111--------");
//    System.out.println(Arrays.toString(cameraIds));
//    System.out.println("11111--------");

    bridge.getActivity().runOnUiThread(new Runnable() {
      @Override
      public void run() {

        FrameLayout containerView = getBridge().getActivity().findViewById(containerViewId);
        if(containerView == null){
          containerView = new FrameLayout(getActivity().getApplicationContext());
          containerView.setId(containerViewId);
          getBridge().getWebView().setBackgroundColor(Color.TRANSPARENT);
          ((ViewGroup) getBridge().getWebView().getParent()).addView(containerView);

          CameraActivity fragment = new CameraActivity();

          FragmentManager fragmentManager = bridge.getActivity().getSupportFragmentManager();
          FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
          fragmentTransaction.add(containerView.getId(),fragment);
          fragmentTransaction.commit();
        } else {
          call.reject("camera already started");
        }
      }
    });
  }

  @PluginMethod
  public void stop(PluginCall call) {

  }
}
